package org.nix.contorller;

import org.nix.dao.CityDistanceJpa;
import org.nix.dao.CityJpa;
import org.nix.dao.UserJpa;
import org.nix.dto.CityWayDto;
import org.nix.entity.City;
import org.nix.entity.User;
import org.nix.service.CityService;
import org.nix.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Create by zhangpe0312@qq.com on 2018/4/19.
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private CityService cityService;

    @Autowired
    private CityJpa cityJpa;

    @Autowired
    private UserJpa userJpa;

    @Autowired
    private CityDistanceJpa cityDistanceJpa;

    @PostMapping(value = "/login")
    public Map<String, Object> login(@RequestParam("userName") String userName,
                                     @RequestParam("password") String password) {

        User user = new User();
        user.setPassword(password);
        user.setUserName(userName);

        Map<String, Object> map = new HashMap<>();
        map.put("result", userService.login(user));
        return map;
    }

    @PostMapping(value = "/getShortWay")
    public Map<String, Object> getShortWay(@RequestParam("startCity") String start,
                                           @RequestParam("endCity") String end) {

        Map<String, Object> map = new HashMap<>();

        City startCity = cityJpa.findCityByCityName(start);
        City endCity = cityJpa.findCityByCityName(end);

        if (startCity == null || endCity == null) {
            map.put("result", "查询失败，没有查询的城市信息");
            return map;
        }

        map.put("result", new CityWayDto(cityService.getMinWay(startCity, endCity),
                cityService.getMinWayLength(startCity, endCity),cityDistanceJpa.findAll()));

        return map;
    }

    @PostMapping(value = "/registered")
    public Map<String,Object> registered(@RequestParam("userName") String userName,
                                         @RequestParam("password") String password){

        Map<String, Object> map = new HashMap<>();

        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);

        user = userJpa.save(user);

        if (user == null){
            map.put("result",false);
            return map;
        }

        map.put("result",true);
        return map;
    }

    @ExceptionHandler(Exception.class)
    public Map<String,Object> exception(Exception e){
        Map<String, Object> map = new HashMap<>();
        map.put("result",false);
        map.put("error",e);
        return map;
    }

}
